import React, { useEffect, useState } from 'react'
import { Form, Input } from 'antd';
import axios from '../../aixos';
import Table from '../../components/Table/Table'
import Search from '../../components/Search/Search';

export default function Guestbook() {
  const [guestbookList, setGuestbookList] = useState([])
  const [total, setTotal] = useState(0)
  const [pageIndex, setPageIndex] = useState(1)
  const pageSize = 10

  const getList = (query = {}) => {
    axios.get('/guestbook', {
      pageIndex,
      pageSize,
      nickname: query.nickname,
      content: query.content
    }).then(res => {
      setGuestbookList(res.data.records)
      setTotal(res.data.total)
    })
  }

  useEffect(() => {
    axios.get('/guestbook', {
      pageIndex,
      pageSize
    }).then(res => {
      setGuestbookList(res.data.records)
      setTotal(res.data.total)
    })
  }, [pageIndex])
  const changePage = (index) => {
    setPageIndex(index)
  }
  
  const del = (id) => {
    axios.delete('/guestbook', {
      id
    }).then(() => {
      setGuestbookList(guestbookList.filter(item => item._id !==id))
    })
  }

  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      render: (_, record) => <span>{record.user.username}</span>,
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      render: (_, record) => <span>{record.user.nickname}</span>,
    },
    {
      title: '内容',
      dataIndex: 'content',
      render: content => <div dangerouslySetInnerHTML={{__html: content}}></div>,
    },
    {
      title: '评论时间',
      dataIndex: 'time',
    }
    // {
    //   title: '操作',
    //   render: (_, record) => (
    //     <Space size="middle">
    //       <Button type='primary' onClick={() => edit(record)}>编辑</Button>
    //       <Button type='danger' onClick={() => del(record._id)}>删除</Button>
    //     </Space>
    //   ),
    // },
  ];

  const search = (form) => {
    const formData = form.getFieldsValue()
    console.log(formData)
    getList(formData)
  }
  return (
    <div>
      <Search submit={search}>
        <Form.Item name='nickname'>
          <Input placeholder="请输入用户昵称" />
        </Form.Item>
        <Form.Item name='content'>
          <Input placeholder="请输入留言内容" />
        </Form.Item>
      </Search>
      <Table rowKey='_id' columns={columns} dataSource={guestbookList}  pagination={{
        current: pageIndex,
        pageSize: pageSize,
        total: total,
        showTotal: () => `共 ${total} 条数据`,
        onChange: changePage
      }} 
      action={{
        delete: {callback: del}
      }}
      >
      </Table>
    </div>
  )
}
